<template>
  <div v-loading.fullscreen="isLoading">
    <el-form label-position="right" label-width="80px" :model="formData">
      <div class="section">
        <div class="section-title">基本信息</div>
        <el-form-item label="商品类目">
          <!-- :props="{ checkStrictly: true }" -->
          <el-cascader
            :options="options"
            style="width:50%"
            v-model="categoryList"
            placeholder="请选择商品类目"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品标题">
          <el-input placeholder="请填写商品名称，最多不能超过30个字符" v-model="formData.tbSpu.title"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input placeholder="请填写商品描述，最多不能超过60个字符" v-model="formData.spudetail.description"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input placeholder="请填写商品商品价格" v-model="formData.tbSpu.priceSpu"></el-input>
        </el-form-item>
        <el-form-item label="运费模板">
          <el-select v-model="formData.tbSpu.freightTId" placeholder="请选择">
            <el-option
              v-for="item in freightArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产岗位">
          <el-select v-model="formData.tbSpu.production" placeholder="请选择">
            <el-option
              v-for="item in productArr"
              :key="item.releId"
              :label="item.releName"
              :value="item.releId"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>

      <div class="section">
        <div class="section-title">商品类目</div>
        <div class="table-body" border style="margin:0 auto 20px">
          <el-table :data="formData.tbSkuList" style="width: 100%">
            <el-table-column prop="title" label="商品类目名称"></el-table-column>
            <el-table-column prop="ownSpec" label="类别"></el-table-column>
            <el-table-column prop="indexs" label="规格"></el-table-column>
            <el-table-column prop="price2" label="价格(元)"></el-table-column>
            <el-table-column prop="stock" label="库存"></el-table-column>
            <!-- <el-table-column prop="useDiamond" label="最大抵扣钻石"></el-table-column> -->
            <el-table-column prop="image" label="图片">
              <template slot-scope="scope">
                <template>
                  <el-image class="banner-image" fit="cover" :src="scope.row.image"></el-image>
                </template>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="prop" label="运费模板">
              <template slot-scope="scope">
                <el-button @click="handleAddFreightClick(scope)" type="text" size="small">设置运费</el-button>
              </template>
            </el-table-column>-->
            <el-table-column label="操作" width="100">
              <template slot="header">
                <el-button @click="handleAddClick" type="primary" size="mini" plain>新增</el-button>
              </template>
              <template slot-scope="scope">
                <el-button @click="handleEditClick(scope)" type="text" size="small">修改</el-button>
                <el-popconfirm title="确定删除此项服务文本？" @onConfirm="handleDeleteClick(scope)">
                  <el-button style="margin-left:20px" size="small" type="text" slot="reference">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="section">
        <div class="section-title">商品介绍</div>
        <div class="section-second">
          <div class="section-second-title">
            <span>商品宣传视频：</span>
            <span style="color:#888888">该视频为宣传作用视频，展示位置为商品轮播图第一张。请保证视频格式正确，且不超过10M</span>
          </div>
          <div class="section-second-content">
            <el-upload
              class="avatar-uploader el-upload--text"
              action
              :show-file-list="false"
              :on-success="handleVideoSuccess"
              :before-upload="beforeUploadVideo"
              :on-progress="uploadVideoProcess"
              :http-request="uploadSwiperFilevideo"
            >
              <video
                v-if="Video !='' && videoFlag == false"
                :src="Video"
                class="avatar"
                controls="controls"
              >您的浏览器不支持视频播放</video>
              <i
                v-else-if="Video =='' && videoFlag == false"
                class="el-icon-plus avatar-uploader-icon"
              ></i>
              <el-progress
                v-if="videoFlag == true"
                type="circle"
                :percentage="videoUploadPercent"
                style="margin-top:30px;"
              ></el-progress>
            </el-upload>
            <!-- <P class="text">请保证视频格式正确，且不超过10M</P> -->
            <!-- <el-upload
              action
              :on-success="onSwiperSuccess"
              ref="swiperRef"
              :http-request="uploadSwiperFile"
              list-type="picture-card"
              :file-list="swiperFileList"
              :limit="5"
              :before-upload="beforeUpload"
              :on-remove="handleSwiperRemove"
              :on-exceed="() => { $message({message : '最多只能上传5张图片'}) }"
            >
              <i class="el-icon-plus"></i>
            </el-upload>-->
          </div>
        </div>
        <div class="section-second">
          <div class="section-second-title">
            <span>商品轮播：</span>
            <span style="color:#888888">上传的第一张图片为商品主图，用于瀑布流展示；图片大小不得超过1MB，最多不超过5张。上传后小程序提供详情页自动放大功能。</span>
          </div>
          <div class="section-second-content">
            <el-upload
              action
              :on-success="onSwiperSuccess"
              ref="swiperRef"
              :http-request="uploadSwiperFile"
              list-type="picture-card"
              :file-list="swiperFileList"
              :limit="5"
              :before-upload="beforeUpload"
              :on-remove="handleSwiperRemove"
              :on-exceed="() => { $message({message : '最多只能上传5张图片'}) }"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </div>
        <div class="section-second">
          <div class="section-second-title">
            <span>商品宣传：</span>
            <span style="color:#888888">商品宣传图片请按顺序上传，展示宽度为（UI出具具体像素宽度），高度不定；图片大小不得超过2MB，最多不超过10张。</span>
          </div>
          <div class="section-second-content">
            <el-upload
              action
              :on-success="onFileSuccess"
              :http-request="uploadFile"
              :limit="10"
              :on-exceed="() => { $message({message : '最多只能上传10张图片'}) }"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </div>
      </div>
      <div class="section" style="border:none">
        <div class="section-title">其他信息</div>
        <el-form-item label="服务信息">
          <el-checkbox-group v-model="checkedService">
            <el-checkbox
              v-for="item in services"
              :label="item.id"
              :value="item.id"
              :key="item.id"
            >{{item.serviceName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- <el-form-item label="线下服务">
          <el-radio-group v-model="formData.tbSpu.offlineService">
            <el-radio label="1">支持线下下单</el-radio>
            <el-radio label="0">不支持线下下单</el-radio>
          </el-radio-group>
        </el-form-item>-->
      </div>

      <div class="section" style="border:none;margin-bottom:200px">
        <el-form-item>
          <el-button @click="submit" :loading="submitDisabled" type="primary" plain>保存并发布商品</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-dialog title="新增商品类目" :visible.sync="dialogVisible" width="30%">
      <add-category ref="addRef" v-if="dialogVisible" @categorySubmit="categorySubmit" />
    </el-dialog>

    <el-dialog title="设置运费" :visible.sync="isAddFreightVisible" width="30%">
      <add-freight
        ref="addFreightRef"
        v-if="isAddFreightVisible"
        @close="isAddFreightVisible = $event"
        @freight="freightSubmit"
      />
    </el-dialog>
  </div>
</template>

<script>
import AddCategory from "./AddCategory";
import AddFreight from "./AddFreight";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      debugger;
      var reg = /^\d+(?=\.{0,1}\d+$|$)/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("销售价格必须为正数"));
      }
    };
    return {
      Video: "",
      videoFlag: false,
      videoUploadPercent: "",
      freightArr: [],
      productArr: [],
      isLoading: false,
      submitDisabled: false,
      dialogVisible: false,
      isAddFreightVisible: false,
      options: [], //类目集合
      categoryList: [],
      services: [], //服务集合
      checkedService: [],
      swiperFileList: [], //轮播图片集合
      fileList: [], //商品宣传集合
      deleteList: [], //删除数组
      deletePostageIds: [], //删除运费数组
      formData: {
        tbSpu: {
          id: undefined, //商品id
          title: "", //商品标题
          subTitle: "", //商品描述
          priceSpu: "", //商品原价
          cid1: "",
          cid2: "",
          serviceIds: "", //服务信息  用逗号分割开
          //offlineService: "1" // 1支持线上 0线下
          freightTId: "", //运费id
          production: "" //生产id
        },
        tbSkuList: [],
        spudetail: {
          description: "",
          images: {
            temBanner: "",
            itemDetail: ""
          },
          video: ""
        }
      },
      rules: {
        priceSpu: [{ validator: validatePass, trigger: "blur" }]
      }
    };
  },

  mounted() {
    let id = this.$route.query.id;
    if (id) {
      this.formData.tbSpu.id = id;
      this.getGoodsDetail();
      document.title = "商品详情";
    }
    this.$service.getAllService().then(res => {
      //console.log(res);
      this.services = res.data || [];
    });
    this.$service.getCategoryList(list => {
      this.options = list;
    });

    this.freightData();
    this.productData();
  },
  methods: {
    productData() {
      this.$service.menuGetProductionList().then(res => {
        if (res.code == "00000") {
          this.productArr = res.data;
        }
      });
    },
    freightData() {
      this.$service.freightTemplateList().then(res => {
        console.log(res.data);
        if (res.code == "00000") {
          this.freightArr = res.data;
        }
      });
    },
    validate(num) {
      var reg = /^\d+(?=\.{0,1}\d+$|$)/;
      if (reg.test(num)) return true;
      return false;
    },

    submit(e) {
      //商品类目
      if (this.categoryList.length == 1) {
        this.formData.cid1 = this.categoryList[0];
      } else if (this.categoryList.length == 2) {
        this.formData.tbSpu.cid1 = this.categoryList[0];
        this.formData.tbSpu.cid2 = this.categoryList[1];
      } else {
        if (this.fileList.length <= 0) {
          this.$message({
            message: "请选择商品类目"
          });
          return;
        }
      }

      if (!this.formData.tbSpu.title) {
        this.$message({
          message: "请填写商品标题"
        });
        return;
      }

      if (!this.formData.spudetail.description) {
        this.$message({
          message: "请填写商品描述"
        });
        return;
      }
      if (!this.formData.tbSpu.priceSpu) {
        this.$message({
          message: "请填写商品价格"
        });
        return;
      }
      if (!this.validate(this.formData.tbSpu.priceSpu)) {
        this.$message({
          message: "商品价格必须为正数"
        });
        return;
      }
      if (this.formData.tbSkuList.length <= 0) {
        this.$message({
          message: "请填写商品类目"
        });
        return;
      }

      //服务信息
      this.formData.tbSpu.serviceIds = this.checkedService.join(",");

      let images = {
        itemDetail: "",
        temBanner: ""
      };

      //轮播信息
      if (this.swiperFileList.length <= 0) {
        this.$message({
          message: "请至少添加一张商品轮播图片"
        });
        return;
      }
      let swiperFileList = JSON.parse(JSON.stringify(this.swiperFileList));
      swiperFileList = swiperFileList.map(item => {
        return item.url;
      });
      images.temBanner = swiperFileList.join(",");

      //商品宣传图片
      if (this.fileList.length <= 0) {
        this.$message({
          message: "请至少添加一张商品宣传图片"
        });
        return;
      }
      //运费模板
      if (this.formData.tbSpu.freightTId == "") {
        this.$message({
          message: "请选择运费模板"
        });
        return;
      }
      let fileList = JSON.parse(JSON.stringify(this.fileList));
      fileList = fileList.map(item => {
        return item.url;
      });
      images.itemDetail = fileList.join(",");
      this.formData.spudetail.images = JSON.stringify(images);
      this.formData.deleteIds = this.deleteList.toString();
      this.formData.deletePostageIds = this.deletePostageIds.toString();
      this.submitDisabled = true;
      this.formData.tbSpu.priceSpu = this.formData.tbSpu.priceSpu * 100;
      this.formData.tbSpu.saleable = "";
      this.formData.spudetail.video = this.Video;
      if (this.formData.tbSpu.id) {
        //debugger;
        this.$service.updateGoods(this.formData).then(res => {
          this.submitDisabled = false;
          if (res.code == "00000") {
            this.$message({
              message: "修改成功",
              type: "success"
            });
            this.formData.tbSpu.priceSpu = this.formData.tbSpu.priceSpu / 100;
            this.$router.back();
          } else {
            this.$message({
              message: res.message || "出错了",
              type: "warning"
            });
          }
        });
      } else {
        this.$service.addGoods(this.formData).then(res => {
          this.submitDisabled = false;
          if (res.code == "00000") {
            this.$message({
              message: "添加成功",
              type: "success"
            });
            this.$router.back();
          } else {
            this.$message({
              message: res.message || "出错了",
              type: "warning"
            });
          }
        });
      }
    },
    //获取商品详情
    getGoodsDetail() {
      this.isLoading = true;
      this.$service
        .getGoodsDetail({ spuId: this.$route.query.id })
        .then(res => {
          this.isLoading = false;
          if (res.code == "00000") {
            console.log(res.data);
            res.data.tbSpu.priceSpu = res.data.tbSpu.priceSpu / 100;

            for (let i = 0; i < res.data.tbSkuList.length; i++) {
              const element = res.data.tbSkuList[i];
              element.price2 = element.price / 100;
            }
            this.formData = res.data;
            //商品类目初始化
            this.categoryList = [
              this.formData.tbSpu.cid1,
              this.formData.tbSpu.cid2
            ];
            let serviceIds = this.formData.tbSpu.serviceIds;
            //服务信息初始化
            if (serviceIds) {
              let list = serviceIds.split(",");
              this.checkedService = list.filter(id => {
                return id !== "";
              });
              this.checkedService = this.checkedService.map(stringId => {
                return Number(stringId);
              });
            }
            //视频初始化
            this.Video = this.formData.spudetail.video || "";
            //商品轮播初始化
            let images = JSON.parse(this.formData.spudetail.images);
            console.log(111, images);
            let swiperFileList = [];
            let swiperFileStr = images.temBanner;
            if (swiperFileStr) {
              let tempList = swiperFileStr.split(",");
              swiperFileList = tempList.filter(item => {
                return item !== "";
              });
              swiperFileList = swiperFileList.map(url => {
                return { url };
              });
            }

            this.swiperFileList = swiperFileList;

            //商品宣传图片初始化
            let fileList = [];
            let fileStr = images.itemDetail;
            if (fileStr) {
              let tempList = fileStr.split(",");
              fileList = tempList.filter(item => {
                return item !== "";
              });
              fileList = fileList.map(url => {
                return { url };
              });
            }
            this.fileList = fileList;
            var ret = JSON.stringify(this.freightArr).indexOf(
              JSON.stringify(this.formData.tbSpu.freightTId)
            );
            console.log("res", ret);
            // this.formData.tbSpu.freightTId = "";
            if(this.formData.tbSpu.production ==0){
                this.formData.tbSpu.production ="";
            };
            if (ret == -1) {
              this.formData.tbSpu.freightTId = "";
            }
          }
        });
    },

    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return;
      }
    },
    beforeUploadVideo(file) {
      console.log("file", file);
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb"
        ].indexOf(file.type) == -1
      ) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("上传视频大小不能超过10MB哦!");
        return false;
      }
    },
    //视频上传

    onSwiperSuccess(response, file, fileList) {
      this.swiperFileList.push(response);
    },
    onFileSuccess(response, file, fileList) {
      this.fileList.push(response);
    },

    handleVideoSuccess(response, file, fileList) {
      //获取上传图片地址
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      this.Video = response.url;
      console.log("response", response);
    },
    uploadVideoProcess(percentage, e) {
      this.videoFlag = true;
      this.videoUploadPercent = percentage * 100;

      return;
      console.log("file.percentage", file.percentage);

      this.videoUploadPercent = file.percentage.toFixed(0);
    },
    uploadSwiperFilevideo(file) {
      console.log("file", file);
      this.$service.uploadFileFunction(file);
    },
    uploadSwiperFile(file) {
      if (
        !(
          file.file.type === "image/jpeg" ||
          file.file.type === "image/jpg" ||
          file.file.type === "image/png"
        )
      ) {
        this.$message.error("请上传图片！");
        return;
      }
      this.$service.uploadFileFunction(file);
    },
    uploadFile(file) {
      if (
        !(
          file.file.type === "image/jpeg" ||
          file.file.type === "image/jpg" ||
          file.file.type === "image/png"
        )
      ) {
        this.$message.error("请上传图片！");
        return;
      }
      this.$service.uploadFileFunction(file);
    },
    handleSwiperRemove(file, fileList) {
      this.swiperFileList = fileList;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    //设置运费模板
    handleAddFreightClick(scope) {
      this.isAddFreightVisible = true;
      this.$nextTick(() => {
        this.$refs.addFreightRef.initData(scope.row, scope.$index);
      });
    },

    //邮费代理的回调
    freightSubmit(list, index, deletePostageIds) {
      console.log(deletePostageIds);
      this.deletePostageIds = deletePostageIds;
      this.isAddFreightVisible = false;
      this.formData.tbSkuList[index].postageList = list;
    },

    //商品类目编辑
    handleEditClick(scope) {
      this.dialogVisible = true;
      let index = scope.$index;
      let json = JSON.parse(JSON.stringify(scope.row));
      this.$nextTick(() => {
        this.$refs.addRef.initData(json, index);
      });
    },
    //商品类目新增
    handleAddClick() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        // this.$refs.addRef.form.image = ''
        this.$refs.addRef.$refs.formRef.resetFields();
      });
    },
    //商品类目新增 回调
    categorySubmit(e, index) {
      if (e) {
        //对象深拷贝
        let json = JSON.parse(JSON.stringify(e));
        if (index != null) {
          //修改
          this.formData.tbSkuList.splice(index, 1, json);
        } else {
          //新增
          this.formData.tbSkuList.push(json);
        }
      }
      this.dialogVisible = false;
    },
    //商品类目删除
    handleDeleteClick(row) {
      console.log(row.row);
      let index = row.$index;
      this.formData.tbSkuList.splice(index, 1);
      if (row.row.id) {
        this.deleteList.push(row.row.id);
      }
    }
  },
  components: {
    "add-category": AddCategory,
    "add-freight": AddFreight
  }
};
</script>

<style lang="scss">
.section {
  width: 90%;
  margin: auto;
  font-size: 14px;
  .section-title {
    height: 50px;
    font-weight: bold;
    display: flex;
    align-items: center;
    position: relative;
    font-size: 16px;
    &::before {
      content: " ";
      position: absolute;
      left: -10px;
      width: 3px;
      height: 12px;
      border-radius: 5px;
      background-color: #409eff;
    }
  }
  .section-second {
    width: 90%;
    margin: 0 auto 20px;
    .section-second-title {
      min-height: 40px;
      margin-bottom: 10px;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 400px !important;
    height: 200px !important;
  }
}
</style>